package com.ews.onlineexchange.validator;

import com.ews.onlineexchange.service.ServiceBuyerService;
import com.ews.onlineexchange.util.SerialnumberUtil;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import javax.inject.Inject;
import javax.inject.Named;

@Named
public class BuyerCreditcodeValidator implements Validator {
	
	@Inject
	ServiceBuyerService serviceBuyerService;

	@Override
	public void validate(FacesContext facesContext,
		      UIComponent component, Object value) throws ValidatorException {
		String creditCode = value.toString();
		if(!SerialnumberUtil.isRightSerialnumber(creditCode)){
			FacesMessage msg =
					new FacesMessage("统一社会信用代码格式有误，请检查","无效的统一社会信用代码");
			msg.setSeverity(FacesMessage.SEVERITY_ERROR);
			throw new ValidatorException(msg);
		}else if (serviceBuyerService.existCreditcode(creditCode)) {
			FacesMessage msg =
	            new FacesMessage("组织机构代码/统一征信代码已存在","无效的组织机构代码/统一征信代码");
			msg.setSeverity(FacesMessage.SEVERITY_ERROR);
	        throw new ValidatorException(msg);
		}
	}

}
